package main

import (
	"flag"
	"fmt"
	"os"
	"strings"
	"time"

	"github.com/rs/xid"
)

var (
	upperCase = flag.Bool("u", false, "返回大写")
	decode    = flag.String("d", "", "解码")
	field     = flag.String("t", "time", "解码字段,可用[time|machine]")
)

func genXid() {
	id := xid.New().String()
	if *upperCase {
		id = strings.ToUpper(id)
	}
	fmt.Println(id)
}

// decodeXid 解析xid
func decodeXid() {
	if *decode == "" {
		fmt.Fprintf(os.Stderr, "please type the xid string")
		flag.PrintDefaults()
		os.Exit(1)
	}
	id, err := xid.FromString(*decode)
	if err != nil {
		fmt.Fprintf(os.Stderr, "%s %s\n", *decode, err.Error())
		os.Exit(1)
	}
	switch *field {
	case "machine":
		fmt.Printf("%x\n", id.Machine())
	case "time":
		fmt.Println(id.Time().Format(time.RFC3339))
	default:
		fmt.Fprintf(os.Stderr, "the field %s is unsupported\n", *field)
		flag.PrintDefaults()
		os.Exit(1)
	}
}

func main() {
	flag.Parse()
	if *decode == "" {
		genXid()
		return
	}
	decodeXid()
}
